<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2018 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Released under the MIT License.
// +----------------------------------------------------------------------
// | Author: 老猫 <thinkcmf@126.com>
// +----------------------------------------------------------------------

namespace app\home\controller;
use think\Db;
class OrderController extends BaseController
{


	/**
	*
	*用户-订单列表
	**/
	public function index()
	{
		$member_id = $this->member_id;

		$courseModel = new \app\home\model\CourseModel();
		$orderModel = new \app\home\model\OrdersModel();
		$coursecodeModel = new \app\home\model\CourseCodeModel();

		//条件搜索
		$status = $this->request->param('status', '');
		$page = $this->request->param('page', 1, 'intval');

		$where = [
			['member_id', '=', $member_id],
			['status', 'in', [1,2,3,4,5]],
		]; 

		if(!empty($status))
		{	
			if(!in_array($status, [1,2,3,4,5]))
			{
				$this->error('订单状态参数非法，传递正确的状态');
			}

			$where = [
				['member_id', '=', $member_id],
				['status', '=', $status],
			];
		}

		$list = $orderModel->memberOrderList($where, $page, 'order_id, order_number, course_id, member_id, status, add_time, pay_money');
		$list = !empty($list) ? $list : [];

		//循环，查找订单课程、订单兑换码
		foreach ($list as $key => $value) {
			//订单课程
			$str = 'id, title, xt_logo';
			$course_info = $courseModel->getCourseInfoDetails($value['course_id'], $str);
			
			$list[$key]['title'] = $course_info['title'];
			$course_info['xt_logo'] = json_img_add_url('/upload/'.$course_info['xt_logo']);
			$list[$key]['course'] = $course_info;
		}

		//echo '<pre>';
		//var_dump($list);return;
		$this->assign('page', $page);
		$this->assign('status', $status);
		$this->assign('list', $list);

        return $this->fetch('order/index');
	}


	/**
	*
	*我的订单- 更多订单
	**/
	public function getOrderList()
	{
		$member_id = $this->member_id;

		$courseModel = new \app\home\model\CourseModel();
		$orderModel = new \app\home\model\OrdersModel();
		$coursecodeModel = new \app\home\model\CourseCodeModel();

		//条件搜索
		$status = $this->request->param('status', '');
		$page = $this->request->param('page', 2, 'intval');

		$where = [
			['member_id', '=', $member_id],
			['status', 'in', [1,2,3,4,5]],
		]; 


		if(!empty($status))
		{	
			if(!in_array($status, [1,2,3,4,5]))
			{
				$this->error('订单状态参数非法，传递正确的状态');
			}

			$where = [
				['member_id', '=', $member_id],
				['status', '=', $status],
			];
		}

		$list = $orderModel->memberOrderList($where, $page, 'order_id, order_number, course_id, member_id, status, add_time, pay_money');
		$list = !empty($list) ? $list : [];

		//循环，查找订单课程、订单兑换码
		foreach ($list as $key => $value) {
			//订单课程
			$str = 'id, title, xt_logo';
			$course_info = $courseModel->getCourseInfoDetails($value['course_id'], $str);
			$course_info['xt_logo'] = json_img_add_url('/upload/'.$course_info['xt_logo']);

			$list[$key]['course'] = $course_info;
		}

		return return_msg(0, 'ok', $list);
	}



	/**
	*
	*订单详情
	*
	**/
	public function orderDetails()
	{
		$member_id = $this->member_id;

		$courseModel = new \app\home\model\CourseModel();
		$orderModel = new \app\home\model\OrdersModel();
		$coursecodeModel = new \app\home\model\CourseCodeModel();
		$memberModel = new \app\home\model\MemberModel();

		//条件搜索
		$order_id = $this->request->param('order_id', '');
		if(empty($order_id))
		{
			$this->error('订单ID错误，参数非法');
		}

		//开始查找
		$where = [
			['member_id', '=', $member_id],
			['order_id', '=', $order_id],
			['status', 'in', [1,2,3,4,5]],
		];

		$info = $orderModel->memberOrderInfo($where);
		
		if(empty($info))
		{
			$this->error('不存在的订单信息，请确认后操作');
		}

		$info['dispatch_time_time'] = strtotime($info['dispatch_time']);

		//查找订单的课程
		$str = 'id, title, xt_logo, attend_type';
		$course_info = $courseModel->getCourseInfoDetails($info['course_id'], $str);
		$course_info['xt_logo'] = json_img_add_url('/upload/'.$course_info['xt_logo']);
		$info['course'] = $course_info;

		//查找订单的兑换码
		if(!empty($info['course_code_id']))
		{
			$code_info = $coursecodeModel->getOrderCodeInfo($info['course_code_id'], 'id, code_name');
			$info['code_info'] = $code_info;
		}

		$meminfo = $memberModel->getMemberIdWhereMemberId($this->member_id, 'member_id, invite');
		
		$this->assign('info', $info);
		$this->assign('invite', $meminfo['invite']);

        return $this->fetch('order/order_details');
	}



	/**
	*
	*用户 - 确认收货
	**/
	public function MemberOrderSubmit()
	{
		$member_id = $this->member_id;
		$orderModel = new \app\home\model\OrdersModel();
		$order_id = $this->request->param('order_id', '', 'intval');
		if(empty($order_id))
		{
			$this->error('订单ID错误，参数非法');
		}

		//开始查找
		$where = [
			['member_id', '=', $member_id],
			['order_id', '=', $order_id],
		];

		$info = $orderModel->memberOrderInfo($where);
		if(empty($info))
		{
			$this->error('不存在的订单信息，请确认后操作');
		}

		//查看订单状态
		if($info['status'] != 2)
		{
			$this->error('请确认订单状态');
		}

		//开始修改状态和收货时间

		$where[] = ['status', '=', 2];

		$update = [
			'status' => 4,
			'delivery_time' => date('Y-m-d H:i:s'),
		];
		$res = $orderModel->updateOrders($where, $update);
		if(empty($res))
		{
			$this->error('确认收货失败，系统错误');
		}else{
			$this->issueAward($order_id);
			$this->redirect('Order/index');
		}
	}



	/**
	*
	*发放-佣金，管理奖励
	*
	**/
	protected function issueAward($order_id)
	{
		$member_id = $this->member_id;
		$orderModel = new \app\home\model\OrdersModel();
		$oaModel = new \app\home\model\OrderAwardModel();
		$memberModel = new \app\home\model\MemberModel();
		$financeModel = new \app\home\model\FinanceModel();
		//查找订单
		$where = [
			['order_id', '=', $order_id],
		];
		$info = $orderModel->memberOrderInfo($where, 'order_id, if_award');
		//只计算已计算的奖励
		if($info['if_award'] == 2)
		{
			//开始发放奖励
			$list = $oaModel->getOrderIdEarningsList($order_id);
			$list = !empty($list) ? $list : [];

			foreach ($list as $key => $value) {
				//直接修改状态，再发放金额
				Db::startTrans();
				$res = [];
				$res[] = $oaModel->updateOrderIdEarnings($value['id'], ['status' => 2]);

				//发放金额
				$memberinfo = $memberModel->getMemberIdWhereMemberId($value['member_id'], 'member_id, money');
				$money = $memberinfo['money'] + $value['money'];//余额+奖励金

				//发放
				$res[] = $memberModel->updateMemberInfo($value['member_id'], ['money' => $money]);

				//查询发放结果
				if(!in_array(false, $res))
				{
					Db::rollback();
				}else{
					$finance = [
						'member_id' => $value['member_id'],
						'type' => $value['award_type'],
						'money' => $value['money'],
						'remark' => ($value['award_type'] == 1) ? '订单收益' : '管理奖励',
						'status' => 2,
						'before_money' => $memberinfo['money'],
						'later_money' => $money,
					];
					$financeModel->addFinance($finance);
					Db::commit();

					//收货成功，通知消息
					if($value['money'] > 0)
					{	
						$source = ($value['award_type'] == 1) ? '订单收益' : '管理奖励';
						$notice_contro = new NoticeController();
						$send_data = [
			                'first' => ['value'=>'您有一笔新收益到账了', 'color'=>"#173177"],
			                'keyword1' => ['value'=> $value['money'], 'color'=>'#173177'],
			                'keyword2' => ['value'=> $source, 'color'=>'#173177'],
			                'keyword3' => ['value'=> date('Y-m-d H:i:s'), 'color'=>'#173177'],
			                'remark' => ['value'=>'点击查看收益详情', 'color'=>'#173177'],
			            ];
			            $return_url = WEB_URL."/award_list?type=".$value['award_type'];
			            $notice_contro->sendNoticeMessage('sy', $send_data, $return_url, '', $value['member_id']);
					}	
				}
			}
			return true;
		}else{
			return false;
		}
	}


	/**
	*
	*收益明细-列表
	*
	**/
	public function awardIndex()
	{
		$type = $this->request->param('type', 1, 'intval');
		$page = $this->request->param('page', 1, 'intval');

		$member_id = $this->member_id;
		$orderModel = new \app\home\model\OrdersModel();
		$oaModel = new \app\home\model\OrderAwardModel();
		$courseModel = new \app\home\model\CourseModel();
		$memModel = new \app\home\model\MemberModel();

		//奖励类型
		if(!empty($type))
		{
			if(in_array($type, [1,2,3,4]))
			{
				$where = [
					['member_id', '=', $member_id],
					['award_type', '=', $type],
					['money', 'gt', 0]
				];
			}else{
				$this->error('订单状态非法，传递正确的状态');
			}	

			
		}
		
		$list = $oaModel->getMemberAwardList($where, $page, 'id, order_id, award_type, award_note, money, status');
		$list = !empty($list) ? $list : [];
		foreach ($list as $key => $value) {
			//找出订单信息
			$order_where = [
				['order_id', '=', $value['order_id']],
			];
			$order_info = $orderModel->memberOrderInfo($order_where, 'order_id, course_id, member_id, pay_money, add_time');

			//找订单课程信息
			$corse_info = $courseModel->getCourseInfoDetails($order_info['course_id'], 'id, title, xt_logo');

			//下单人信息
			$member_info = $memModel->getMemberIdWhereMemberId($order_info['member_id'], 'member_id, nickname, logo, invite');

			$list[$key]['pay_money'] = $order_info['pay_money'];//交易金额
			$list[$key]['pay_add_time'] = $order_info['add_time'];//下单时间
			$list[$key]['course_id'] = $order_info['course_id'];
			$list[$key]['title'] = $corse_info['title'];
			$list[$key]['xt_logo'] = json_img_add_url('/upload/'.$corse_info['xt_logo']);
			$list[$key]['nickname'] = $member_info['nickname'];
			$list[$key]['logo'] = $member_info['logo'];
		}


		//找出自己的邀请码
		$meminfo = $memModel->getMemberIdWhereMemberId($this->member_id, 'member_id, invite');   

		if($this->request->isAjax()){
			return return_msg(200, 'ok', ['type' => $type, 'list' => $list, 'invite' => $meminfo['invite']]);
		}else{
			$this->assign('page', $page);
			$this->assign('type', $type);
			$this->assign('list', $list);
			$this->assign('invite', $meminfo['invite']);
	 		return $this->fetch('order/award_index');
		}

		
	}

	
}